/* 单独为订单导入(formdata)配置的ajax请求 */

import axios from 'axios';
import qs from 'qs';
import {
    Message,
    Loading
} from 'element-ui';
import {
    baseURL
} from '@/utils/config';
import router from '@/router';
import store from '@/store/index';
axios.defaults.withCredentials = true;
const ajax = axios.create({
    baseURL,
    withCredentials: false,
    timeout: 10*60*1000 // request timeout
})
let loadingInstance;
ajax.interceptors.request.use(
    config => {
        loadingInstance = Loading.service({
            lock: true,
            text: '数据上传中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        return config

    }, error => {
        if (loadingInstance) {
            loadingInstance.close();
        }
        return Promise.reject(error)
    })

ajax.interceptors.response.use(
    response => {
        const {
            code
        } = response.data;
        if (code !== 20000 && code !== 800000 && code !== 500203) { // 800000是轮询成功的情况。需要加一层判断, 是登录失效还是接口错误
            if (code === 300201 || code === 300202 || code === 300203 || code === 300301 || code === 300401|| code === 400201|| code === 400202|| code === 400203|| code === 400204) {
                Message.closeAll()
                Message.error('登录超时,请重新登录');
                store.dispatch('LoginOut').then(function () {
                    router.push({path: '/login'});
                })
            }
            Message.closeAll();
            if (response.data.message) {
                Message.error(response.data.message);
            }
        }
        if (loadingInstance) {
            loadingInstance.close();
        }
        return response.data

    }, err => {
        console.log(err)
        if (loadingInstance) {
            loadingInstance.close();
        }
        const {
            response,
            request
        } = err;
        const {
            status
        } = request;
        if (!response) {
            Message.closeAll();
            Message({
                message: `${status}:网络连接失败`,
                type: 'error',
                duration: 25 * 1000
            })
        } else {
            Message.closeAll();
            Message.error(`${status}:网络连接失败`);
        }

        return Promise.reject(err)
    })

export default ajax;